<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- 
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License. 
-->
<html>
<head>
    <link type="text/css" rel="stylesheet" href="https://struts.apache.org/css/default.css">
    <style type="text/css">
        .dp-highlighter {
            width:95% !important;
        }
    </style>
    <style type="text/css">
        .footer {
            background-image:      url('https://cwiki.apache.org/confluence/images/border/border_bottom.gif');
            background-repeat:     repeat-x;
            background-position:   left top;
            padding-top:           4px;
            color:                 #666;
        }
    </style>
    <link href='https://struts.apache.org/highlighter/style/shCoreStruts.css' rel='stylesheet' type='text/css' />
    <link href='https://struts.apache.org/highlighter/style/shThemeStruts.css' rel='stylesheet' type='text/css' />
    <script src='https://struts.apache.org/highlighter/js/shCore.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushPlain.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushXml.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushJava.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushJScript.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushGroovy.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushBash.js' type='text/javascript'></script>
    <script type="text/javascript">
        SyntaxHighlighter.defaults['toolbar'] = false;
        SyntaxHighlighter.all();
    </script>
    <script type="text/javascript" language="javascript">
        var hide = null;
        var show = null;
        var children = null;

        function init() {
            /* Search form initialization */
            var form = document.forms['search'];
            if (form != null) {
                form.elements['domains'].value = location.hostname;
                form.elements['sitesearch'].value = location.hostname;
            }

            /* Children initialization */
            hide = document.getElementById('hide');
            show = document.getElementById('show');
            children = document.all != null ?
                    document.all['children'] :
                    document.getElementById('children');
            if (children != null) {
                children.style.display = 'none';
                show.style.display = 'inline';
                hide.style.display = 'none';
            }
        }

        function showChildren() {
            children.style.display = 'block';
            show.style.display = 'none';
            hide.style.display = 'inline';
        }

        function hideChildren() {
            children.style.display = 'none';
            show.style.display = 'inline';
            hide.style.display = 'none';
        }
    </script>
    <title>HTTP Session</title>
</head>
<body onload="init()">
<table border="0" cellpadding="2" cellspacing="0" width="100%">
    <tr class="topBar">
        <td align="left" valign="middle" class="topBarDiv" align="left" nowrap>
            &nbsp;<a href="home.html">Home</a>&nbsp;&gt;&nbsp;<a href="tutorials.html">Tutorials</a>&nbsp;&gt;&nbsp;<a href="getting-started.html">Getting Started</a>&nbsp;&gt;&nbsp;<a href="http-session.html">HTTP Session</a>
        </td>
        <td align="right" valign="middle" nowrap>
            <form name="search" action="https://www.google.com/search" method="get">
                <input type="hidden" name="ie" value="UTF-8" />
                <input type="hidden" name="oe" value="UTF-8" />
                <input type="hidden" name="domains" value="" />
                <input type="hidden" name="sitesearch" value="" />
                <input type="text" name="q" maxlength="255" value="" />
                <input type="submit" name="btnG" value="Google Search" />
            </form>
        </td>
    </tr>
</table>

<div id="PageContent">
    <div class="pageheader" style="padding: 6px 0px 0px 0px;">
        <!-- We'll enable this once we figure out how to access (and save) the logo resource -->
        <!--img src="/wiki/images/confluence_logo.gif" style="float: left; margin: 4px 4px 4px 10px;" border="0"-->
        <div style="margin: 0px 10px 0px 10px" class="smalltext">Apache Struts 2 Documentation</div>
        <div style="margin: 0px 10px 8px 10px"  class="pagetitle">HTTP Session</div>

        <div class="greynavbar" align="right" style="padding: 2px 10px; margin: 0px;">
            <a href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=27838912">
                <img src="https://cwiki.apache.org/confluence/images/icons/notep_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Edit Page"></a>
            <a href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=27838912">Edit Page</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/listpages.action?key=WW">
                <img src="https://cwiki.apache.org/confluence/images/icons/browse_space.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Browse Space"></a>
            <a href="https://cwiki.apache.org/confluence/pages/listpages.action?key=WW">Browse Space</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=WW&fromPageId=27838912">
                <img src="https://cwiki.apache.org/confluence/images/icons/add_page_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Add Page"></a>
            <a href="https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=WW&fromPageId=27838912">Add Page</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/createblogpost.action?spaceKey=WW&fromPageId=27838912">
                <img src="https://cwiki.apache.org/confluence/images/icons/add_blogentry_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Add News"></a>
            <a href="https://cwiki.apache.org/confluence/pages/createblogpost.action?spaceKey=WW&fromPageId=27838912">Add News</a>
        </div>
    </div>

    <div class="pagecontent">
        <div class="wiki-content">
            <div id="ConfluenceContent"><div class="confluence-information-macro confluence-information-macro-information"><span class="aui-icon aui-icon-small aui-iconfont-info confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>The example code for this tutorial, http_session, is available at <a shape="rect" class="external-link" href="https://github.com/apache/struts-examples" rel="nofollow">https://github.com/apache/struts-examples</a></p></div></div><h3 id="HTTPSession-Introduction">Introduction</h3><p>Your Struts 2 application may need to access the HTTP session object. Struts 2 provides an interface, <a shape="rect" class="external-link" href="http://struts.apache.org/2.3.1.2/struts2-core/apidocs/org/apache/struts2/interceptor/SessionAware.html">SessionAware</a>, that your Action class should implement to obtain a reference to the HTTP session object.</p><div class="confluence-information-macro confluence-information-macro-tip"><span class="aui-icon aui-icon-small aui-iconfont-approve confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>The <a shape="rect" class="external-link" href="http://struts.apache.org/mail.html">Struts 2 user mailing list</a> is an excellent place to get help. If you are having a problem getting the tutorial example applications to work search the Struts 2 mailing list. If you don't find an answer to your problem, post a question on the mailing list.</p></div></div><h3 id="HTTPSession-SessionAwareInterface">SessionAware Interface</h3><p>The SessionAware interface has one method, setSession, that your Action class will need to override. In the example application (see above), the HelloWorldAction class implements the SessionAware interface and includes this code:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>HelloWorldAction.java setSession Method</b></div><div class="codeContent panelContent pdl">
<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">private Map&lt;String, Object&gt; userSession ;

public void setSession(Map&lt;String, Object) session) {

   userSession = session ;

}

</pre>
</div></div><p>The Struts 2 framework has an interceptor that will inject the HTTP session object into the Action class by calling the setSession method.</p><h3 id="HTTPSession-UsingtheHTTPSessionObjectInTheActionClass">Using the HTTP Session Object In The Action Class</h3><p>The example application keeps track of how many times the user clicks on a Hello link or submits the hello form. It stores this count in the HTTP session object in the increaseHelloCount method.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>HelloWorldAction.java increaseHelloCount Method</b></div><div class="codeContent panelContent pdl">
<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">private void increaseHelloCount() {
			
   Integer helloCount = (Integer) userSession.get(HELLO_COUNT);
		
   if (helloCount == null ) {
		
     helloCount = 1;
			
   } else {
			
     helloCount++;

   }
		
   userSession.put(HELLO_COUNT, helloCount);
	
}


</pre>
</div></div><p>When the increaseHelloCount method is called from within the execute method, the userSession object is a reference to the HTTP session object injected by the Struts 2 framework. So any objects stored in the HTTP session can be retrieved using the userSession object and any objects stored in the userSession object will be stored in the HTTP session object.</p><h3 id="HTTPSession-AccessingHTTPSessionObjectsInTheView">Accessing HTTP Session Objects In The View</h3><p>Struts 2 provides an easy way to get an object stored in the HTTP session from within the view page. In the example application is HelloWorld.jsp with this markup:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>HelloWorld.jsp Get helloCount Value From HTTP Session</b></div><div class="codeContent panelContent pdl">
<pre class="brush: html; gutter: false; theme: Default" style="font-size:12px;">   &lt;p&gt;I've said hello to you &lt;s:property value="#session.helloCount" /&gt; times!&lt;/p&gt;

</pre>
</div></div><p>The s:property tag's value attribute has a value of #session.helloCount. The "#" before the word session tells the Struts framework to look in the session scope for a key of "helloCount" (which is the value of the String constant HELLO_COUNT referenced in method increaseHelloCount). Struts will get the object mapped to helloCount key and then call that object's toString method to determine what to display in the view page.</p><h3 id="HTTPSession-BestPracticesWhenUsingSessionAware">Best Practices When Using SessionAware</h3><p>Using SessionAware does introduce a potential security vulnerability that you should mitigate by also following these practices in the Action class that implements the SessionAware interface.</p><ol><li>Do not have a public Map&lt;String, Object) getSession method in the Action class. You only need a public void setSession method to implement the SessionAware interface.</li><li>Also have the Action class implement the <a shape="rect" class="external-link" href="http://struts.apache.org/2.3.1.2/xwork-core/apidocs/com/opensymphony/xwork2/interceptor/ParameterNameAware.html">ParameterNameAware interface</a> and override its acceptableParameterName method:</li></ol><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>HelloWorldAction.java acceptableParameterName Method</b></div><div class="codeContent panelContent pdl">
<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">	public boolean acceptableParameterName(String parameterName) {
		
		boolean allowedParameterName = true ;
		
		if ( parameterName.contains("session")  || parameterName.contains("request") ) {
		
			allowedParameterName = false ;
			
		} 
		
		return allowedParameterName;
	}

</pre>
</div></div><p>This method will be called by the Struts 2 framework for each parameter in the request scope. By returning false if the parameter name contains "session" we are telling the Struts 2 framework to ignore that parameter. This will prevent a malicious user from trying to hack the HTTP session object.</p><p>Instead of having each action that implements SessionAware also implement the ParameterNameAware interface you can tell the params interceptor to exclude specific request attributes for all actions in a package. In struts.xml configure the struts-default set of interceptors as follows:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>struts.xml configure params interceptor</b></div><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">	&lt;package name="basicstruts2" extends="struts-default"&gt;

 		&lt;interceptors&gt;
	 		&lt;interceptor-stack name="appDefault"&gt;
	        	 &lt;interceptor-ref name="defaultStack"&gt;
	      			&lt;param name="exception.logEnabled"&gt;true&lt;/param&gt;
	      			&lt;param name="exception.logLevel"&gt;ERROR&lt;/param&gt;
	      			&lt;param name="params.excludeParams"&gt;dojo\..*,^struts\..*,^session\..*,^request\..*,^application\..*,^servlet(Request|Response)\..*,parameters\...*&lt;/param&gt;
	   			&lt;/interceptor-ref&gt;
	 	    &lt;/interceptor-stack&gt;
		&lt;/interceptors&gt;
		
		&lt;default-interceptor-ref name="appDefault" /&gt;

</pre>
</div></div><p>The above code will ensure that every action in the "basicstruts2" package that implements the SessionAware interface will exclude from processing parameters that starts with the strings provided in the params.excludeParams noded.</p><p>The example project includes both methods for mitigating the SessionAware security vulnerability.</p><div class="confluence-information-macro confluence-information-macro-tip"><span class="aui-icon aui-icon-small aui-iconfont-approve confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>Note the same issue exists if you implement the ServletRequestAware interface, which is why the above method returns false if the parameter name contains "request".</p></div></div><h3 id="HTTPSession-Summary">Summary</h3><p>When your Action class needs to access the HTTP session object implement the SessionAware interface and override the setSession method. Be sure to also implement the ParameterNameAware interface and override the acceptableParameterName method to mitigate a potential security vulnerability. If you have multiple actions that implement SessionAware then consider modifying the params interceptor's excludeParams value as part of your Struts 2 package setup.</p></div>
        </div>

        
    </div>
</div>
<div class="footer">
    Generated by CXF SiteExporter
</div>
</body>
</html>
